from flask import Blueprint
from app.common.result import trueReturn, falseReturn
from app.api import handle_error, verify_params
from flask import request, g, jsonify
from app.models.Student import Student, Position
from app.api import api_URL, app_id, app_secret
from app.util.zhenzismsclient import ZhenziSmsClient as MessageClient
import json
from flask_socketio import emit

student_blueprint = Blueprint('student_blueprint', __name__, url_prefix='/student')


@student_blueprint.before_request
@handle_error
def before_request():
    if (request.method == 'POST' or request.method == 'PUT') and request.get_data():
        g.data = request.get_json()
    elif request.method == 'GET' or request.method == 'DELETE':
        g.data = request.args
    else:
        g.data = {}


@student_blueprint.route('', methods=['GET'])
@handle_error
@verify_params(params=['by'])
def get_students():
    by = g.data.get('by', None)
    if by == 'studentId':
        studentId = g.data.get('studentId', None)
        if not studentId:
            return falseReturn(msg='未提供studentId，请检查')
        students = Student.get_by_studentId(studentId=studentId)
        if not students:
            return falseReturn(None, '学生不存在')
        students = [students]
    elif by == 'all':
        students = Student.get_all()
    elif by == 'roomId':
        roomId = g.data.get('roomId', None)
        if not roomId:
            return falseReturn(msg='未提供roomId，请检查')
        students = Student.get_by_roomId(roomId=roomId)
    else:
        return falseReturn(msg='请求方式有误，请检查')

    return trueReturn({
        'students': students,
        'count': len(students)
    })


@student_blueprint.route('/data', methods=['GET'])
@handle_error
@verify_params(params=['dataType'])
def get_data():
    dataType = g.data.get('dataType', None)
    if dataType == 'check':
        checked, unchecked = Student.get_check()
        return trueReturn(data={
            "checked": checked,
            "unchecked": unchecked
        }, msg='查询成功')
    else:
        return falseReturn(msg='请求类型错误，请检查')


@student_blueprint.route('', methods=['PUT'])
@handle_error
@verify_params(params=['studentId'])
def update_student():
    studentId = g.data['studentId']
    # roomId = g.data.get('roomId', None)
    name = g.data.get('name', None)
    phone = g.data.get('phone', None)
    status = g.data.get('status', None)
    # warnOpened = g.data.get('warnOpened', None)

    student = Student.get_by_studentId(studentId=studentId)
    if not student:
        return falseReturn(msg='学生不存在')
    else:
        student.update(studentId=studentId, name=name, phone=phone, status=status)
        student.reload()
        return trueReturn(data={"student": student}, msg='修改成功')


@student_blueprint.route('/check', methods=['POST'])
@handle_error
@verify_params(params=['by'])
def remind_sms():
    def get_params(single_student):
        name = single_student['name']
        phone = single_student['phone']
        if not phone:
            return None

        return {
            'number': phone,
            'templateId': '5121',
            'templateParams': [name if name is not None else '同学']
        }

    client = MessageClient(api_URL, app_id, app_secret)
    by = g.data.get('by', None)
    if by == 'studentId':
        studentId = g.data.get('studentId', None)
        if not studentId:
            return falseReturn(msg='请提供studentId')
        student = Student.get_by_studentId(studentId=studentId)
        if not student:
            return falseReturn(msg='学生不存在')
        params = get_params(student)
        if params is None:
            return falseReturn(msg='该学生未填写手机号，无法发送')
        result = json.loads(client.send(params))
        print('result', result['code'])
        print('data', result['data'])
        if result['code'] == 0:
            return trueReturn(msg='发送成功')
        else:
            return falseReturn(msg=result['data'])
    elif by == 'all':
        result_list = []
        students = Student.get_unchecked()
        for student in students:
            params = get_params(student)
            if params is None:
                result_list.append({
                    'studentId': student['studentId'],
                    'result': 1,
                    'msg': '该学生未填写手机号，无法发送'
                })
            else:
                result = json.loads(client.send(params))
                result_list.append({
                    'studentId': student['studentId'],
                    'result': result['code'],
                    'msg': result['data']
                })

        for result in result_list:
            if result['result'] != 0:
                return falseReturn(data={"results": result_list}, msg='发送短信存在问题')
        return trueReturn(data={"results": result_list}, msg='全部发送成功')
    else:
        return falseReturn(msg='请求类型错误，请检查')


@student_blueprint.route('/check', methods=['PUT'])
@handle_error
@verify_params(params=['studentId', 'longitude', 'latitude'])
def check():
    studentId = g.data.get('studentId', None)
    longitude = g.data.get('longitude', None)
    latitude = g.data.get('latitude', None)

    student = Student.get_by_studentId(studentId)
    if student is None:
        return falseReturn(msg='学生不存在')
    else:
        position = Position(longitude=longitude, latitude=latitude)
        student.update(isChecked=True, position=position)
        return trueReturn(msg='打卡成功')
